import cgi
import datetime
import urllib
import wsgiref.handlers

import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

view_path = os.path.join(os.path.dirname(__file__), 'views')

### MODELS ### 
  
from model.model import *


### CLASS WEB HANDEL ###
class BaseHandle(webapp.RequestHandler):
	def auth(self):
		user = users.get_current_user()
		if not user:
			self.redirect(users.create_login_url("/"))
		else:
			return user.email()
	
	def render(self, view_name, values):
		path = os.path.join(view_path, view_name)
		self.response.out.write(template.render(path, values))
  
class MainPage(BaseHandle):	
	def get(self):
		user_email = self.auth()
		
		categories = Categories.get_all(user_email)
		space = "........................................................................."
		len_cat = len(categories)
		for i in range(len_cat):
			#move name to right depen on level
			categories[i].name = space[:categories[i].level*3] + categories[i].name
			
		#render
		template_values = {
			'categories': categories
		}
		self.render("index.html", template_values);
		
		

		
class CategoryPage(BaseHandle):
	def get(self):
		user_email = self.auth()			
		
		#render
		template_values = {
			'title': "Category"
		}
		path = os.path.join(view_path, 'category.html')
		self.response.out.write(template.render(path, template_values))
	
	#Handle for ajax call, method = post
	#Path: /category
	#Get new category information and create new. When finish return result value
	def post(self):
		user_email = self.auth()
		
		category = Categories(parent=user_key(user_email))
		
		category.name = self.request.get('name')
		category.father_id = int(self.request.get('father'))
		category.level = int(self.request.get('level'))
		category.put()
		
		self.response.out.write("ok")
		#self.redirect('/category')

class CategoryListAction(BaseHandle):
	def get(self):
		user_email = self.auth()
		
		categories = Categories.get_all(user_email)	
					
		#render
		template_values = {
			'categories': categories
		}
		path = os.path.join(view_path, 'category_list.html')
		self.response.out.write(template.render(path, template_values))

class CategoryDelAction(BaseHandle):
	
	def get(self):
		user_email = self.auth()		
		#try:
			# Delete category
		cat_id = int(self.request.get('id'))
		self.deleteWithChild(cat_id, user_email)			
		self.response.out.write("ok")
		#except:
		#	self.response.out.write("faild")
			
	# Delete a category and all it's children
	# id: Number
	def deleteWithChild(self, id, user_email):
		child_cats = Categories.gql("WHERE father_id = :id", id = int(id))
		
		# Delete children
		for cat in child_cats:
			self.deleteWithChild(cat.key().id(), user_email)
		
		# Delete curent category
		category = Categories.get_by_id(int(id), parent=user_key(user_email))
		category.delete()

		
application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/category', CategoryPage),
  ('/category/all', CategoryListAction),
  ('/category/del', CategoryDelAction),
  
], debug=True)


def main():
  run_wsgi_app(application)


if __name__ == '__main__':
  main()